import { _decorator, Component, director, EditBox, Node } from "cc";
import NetworkManager from "../Global/NetworkManager";
import { ApiMsgEnum } from "../Common";
import DataManager from "../Global/DataManager";
import { SceneEnum } from "../Enum";
const { ccclass, property } = _decorator;

@ccclass("LoginManager")
export class LoginManager extends Component {
  inputName: EditBox;

  protected onLoad(): void {
    this.inputName = this.node.getComponentInChildren(EditBox);
    director.preloadScene(SceneEnum.Hall);
  }

  async start() {
    await this.connetServer();
  }

  update(deltaTime: number) {}

  login() {
    let nickname = this.inputName;
  }

  async connetServer() {
    if (!(await NetworkManager.Instance.connect().catch(() => false))) {
      await new Promise((rs) => setTimeout(rs, 1000));
      await this.connetServer();
    }
  }

  async handleClick() {
    if (!NetworkManager.Instance.isConnected) {
      await NetworkManager.Instance.connect();
      console.log("未连接");
      return;
    }

    const username = this.inputName.string;
    if (!username) {
      console.log("Please enter a username");
      return;
    }

    const { success, error, res } = await NetworkManager.Instance.callApi(
      ApiMsgEnum.ApiPlayerJoin,
      { nickname: username }
    );
    if (!success) {
      console.log(error);
      return;
    }

    DataManager.Instance.myPlayerId = res.player.id;

    console.log("res", res);
    director.loadScene(SceneEnum.Hall);
  }
}
